<?php
/**
 * Created by PhpStorm.
 * User: win7
 * Date: 2018/5/21 0021
 * Time: 14:34
 */

namespace Wx\Controller;

use Think\Controller;

use Wx\Model\SendMsg;
use Wx\Model\shareModel;

class ForetasteOrderController extends CommonController
{
    public function _initialize(){

        parent::_initialize();

        $goods = M("foretaste_goods")->where("state = 1")->select();//所有商品

        foreach($goods as $gk => $gv){
            //活动商品--库存为0结束
            if ($gv['num'] > 0){
                // 活动商品——活动时间内
                if (time() <= $gv['endtime']) {

                    //获取该商品活动的商品订单--完成集赞的
                    $order = M("foretaste_order")->where("g_id = {$gv['id']}  AND population >= {$gv['praise_num']} AND state = 0")->select();

                    //订单处理
                    foreach ($order as $ok => $ov){
                        //申请中的订单
                        $usetime = time()-$ov['addtime'];//参与时间
                        M("foretaste_order")->where("id = {$ov['id']}")->save(['endtime'=>time(),'state'=>1,'usetime'=>$usetime]);//完成点赞，自动成功
                        M('foretaste_goods')->where("id = {$ov['g_id']}")->setDec('num',1);//减库存
//                        $member = M('member')->where("id = {$ov['u_id']}")->find();
//                        $credit = $member['credit1']+floatval($ov['price']);
//                        $save_credit = M('member')->where("id = {$ov['u_id']}")->save(['credit1'=>$credit]);
//                        if ($save_credit){
                        //积分记录
//                            $credit_log = array(
//                                'u_id' => $member['id'],
//                                'credit_type' => 'credit1',
//                                'change_number' => $ov['price'],
//                                'change_type' => '+',
//                                'reason' => '试吃活动失败返还',
//                                'changetime' => time()
//                            );
//                            M("member_credit_log")->add($credit_log);//积分记录
//                            M("voice")->add(['u_id'=>$ov['u_id'],'content'=>'因未能完成集赞，您参与的试吃活动失败,积分已退回到您的账户!','sendtime'=>time()]);
//                            D("SendMsg")->senderror($ov['u_id'],'试吃','试吃申请',"申请失败","因未能完成集赞，您参与的试吃活动失败!","点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/ForetasteOrder/order/oid/".$ov['id']);
                        M("voice")->add(['u_id'=>$ov['u_id'],'content'=>'您成功参与了试吃活动，请等待发货通知!','sendtime'=>time()]);
                        D("SendMsg")->sendsuccess($ov['u_id'],'试吃','试吃申请',date("Y-m-d H:i:s",$ov['addtime']),"点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/ForetasteOrder/order/oid/".$ov['id']);
//                        }//end if

//                        //待成功的订单
//                        if($ov['state'] == 7){
//                            $order_success = M("foretaste_order")->where("g_id = {$gv['id']} AND state = 7")->order('usetime')->select();//订单排名
//
//                            foreach ($order_success as $sk => $sv){
//                                if($sk < 3){
//                                    M("foretaste_order")->where("id = {$sv['id']}")->save(['state'=>1]);//完成申请
//                                    M("voice")->add(['u_id'=>$sv['u_id'],'content'=>'您成功参与了试吃活动，请等待发货通知!','sendtime'=>time()]);
//                                    D("SendMsg")->sendsuccess($sv['u_id'],'试吃','试吃申请',date("Y-m-d H:i:s",$sv['addtime']),"点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/ForetasteOrder/order/oid/".$sv['id']);
//                                }else{
//                                    M("foretaste_order")->where("id = {$sv['id']}")->save(['state'=>6]);//申请失败
//                                    $member = M('member')->where("id = {$sv['u_id']}")->find();
//                                    $credit = $member['credit1']+floatval($sv['price']);
//                                    $save_credit = M('member')->where("id = {$sv['u_id']}")->save(['credit1'=>$credit]);
//                                    if ($save_credit){
//                                        //积分记录
//                                        $credit_log = array(
//                                            'u_id' => $member['id'],
//                                            'credit_type' => 'credit1',
//                                            'change_number' => $sv['price'],
//                                            'change_type' => '+',
//                                            'reason' => '试吃活动失败返还',
//                                            'changetime' => time()
//                                        );
//                                        M("member_credit_log")->add($credit_log);//积分记录
//                                        M("voice")->add(['u_id'=>$sv['u_id'],'content'=>'未能成为前三名，您参与的试吃活动失败,积分已退回到您的账户!','sendtime'=>time()]);
//                                        D("SendMsg")->senderror($sv['u_id'],'试吃','试吃申请',"申请失败","未能成为前三名，您参与的试吃活动失败!","点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/ForetasteOrder/order/oid/".$sv['id']);
////                                    M("voice")->add(['u_id'=>$sv['u_id'],'content'=>'试吃活动失败，退回'.$sv['price'].'积分','sendtime'=>time()]);
//                                    }//end if
//                                }//end if
//                            }//end foreach
//                        }//end if

                    }//end foreach
//                    M("foretaste_goods")->where("id = {$gv['id']}")->save(['state' => 4]);//结束活动
                }else{
                    //获取该商品活动的商品订单--未完成集赞的
                    $order = M("foretaste_order")->where("g_id = {$gv['id']} AND state = 0")->select();
                    //订单处理
                    foreach ($order as $ok => $ov){
                        //申请中的订单
                        M("foretaste_order")->where("id = {$ov['id']}")->save(['state'=>6]);//完成点赞，自动失败
                        $save_credit = M('member')->where("id = {$ov['u_id']}")->setInc('credit1',floatval($ov['price']));//退积分
                        if ($save_credit){
                            //积分记录
                            $credit_log = array(
                                'u_id' => $ov['u_id'],
                                'credit_type' => 'credit1',
                                'change_number' => $ov['price'],
                                'change_type' => '+',
                                'reason' => '试吃活动失败返还',
                                'changetime' => time()
                            );
                            M("member_credit_log")->add($credit_log);//积分记录
                            M("voice")->add(['u_id'=>$ov['u_id'],'content'=>'您参与的试吃活动失败,积分已退回到您的账户!','sendtime'=>time()]);
                            D("SendMsg")->senderror($ov['u_id'],'试吃','试吃申请',"申请失败","您参与的试吃活动失败!","点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/ForetasteOrder/order/oid/".$ov['id']);
                            M("voice")->add(['u_id'=>$ov['u_id'],'content'=>'试吃活动失败，退回'.$ov['price'].'积分','sendtime'=>time()]);
                        }//end if
                    }//end foreach $order
                    M("foretaste_goods")->where("id = {$gv['id']}")->save(['state' => 4]);//结束活动
                }//end if $gv.endtime
            }else{
                //获取该商品活动的商品订单--未完成集赞的
                $order = M("foretaste_order")->where("g_id = {$gv['id']} AND state = 0")->select();
                //订单处理
                foreach ($order as $ok => $ov){
                    //申请中的订单
                    M("foretaste_order")->where("id = {$ov['id']}")->save(['state'=>6]);//完成点赞，自动失败
                    $save_credit = M('member')->where("id = {$ov['u_id']}")->setInc('credit1',floatval($ov['price']));//退积分
                    if ($save_credit){
                        //积分记录
                        $credit_log = array(
                            'u_id' => $ov['u_id'],
                            'credit_type' => 'credit1',
                            'change_number' => $ov['price'],
                            'change_type' => '+',
                            'reason' => '试吃活动失败返还',
                            'changetime' => time()
                        );
                        M("member_credit_log")->add($credit_log);//积分记录
                        M("voice")->add(['u_id'=>$ov['u_id'],'content'=>'您参与的试吃活动失败,积分已退回到您的账户!','sendtime'=>time()]);
                        D("SendMsg")->senderror($ov['u_id'],'试吃','试吃申请',"申请失败","您参与的试吃活动失败!","点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/ForetasteOrder/order/oid/".$ov['id']);
                        M("voice")->add(['u_id'=>$ov['u_id'],'content'=>'试吃活动失败，退回'.$ov['price'].'积分','sendtime'=>time()]);
                    }//end if
                }//end foreach $order
                M("foretaste_goods")->where("id = {$gv['id']}")->save(['state' => 4]);//结束活动
            }//end if $gv.num
        }//end foreach $goods

        //扶贫大使活动时间-start
        $helppoor = M("helppoor")->select();
        if (isset($helppoor)){
            foreach ($helppoor as $hk => $hv){
                if (time() >= $hv['starttime'] && $hv['state'] == 0){
                    M("helppoor")->where("id = {$hv['id']}")->save(['state'=>1]);//开始排名
                }//end if
                if (time() > $hv['endtime'] && $hv['state'] == 1){
                    M("helppoor")->where("id = {$hv['id']}")->save(['state'=>2]);//结束排名
                    $ranking_info = M("foretaste_ranking")->where("h_id = {$hv['id']}")->order('eva_num desc')->select();//查看排名
                    $member_id = array();
                    foreach ($ranking_info as $k => $v){
                        if (!array_key_exists($v['c_id'],$member_id)){
                            $member_id[$v['c_id']]=$v['u_id'];//获取小区第一
                            M("voice")->add(['u_id'=>$v['u_id'],'content'=>'恭喜您成为扶贫大使，获得恩施三天游的机会!','sendtime'=>time()]);//通知
                            D("SendMsg")->sendsuccess($v['u_id'],'扶贫排行','扶贫大使排行，恩施3日游',date("Y-m-d H:i:s",time()),"点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/Foretaste/helppoor");
                        }//end if
                    }//end foreach
                    $member_id=implode(',',array_slice($member_id,0,$hv['success_num']));//转换为字符串
                    //处理多余的逗号
                    $member_id=preg_replace('/(,)+/i',',',$member_id);
                    $member_id=rtrim($member_id,',');//去尾
                    $member_id=ltrim($member_id,',');//去头
                    M("helppoor")->where("id = {$hv['id']}")->save(['member_ranking'=>$member_id]);//成功用户排名
                }//end if
            }//end foreach
        }//end if
        //扶贫大使活动时间-end

        //未关注的存储到xcache中，程序轮询检测（关注后推送最近浏览的商品信息）-start
        if(session('focus')==0 && session('u_id')>0){
            $focusmsg=new \Wx\Controller\AutofocusmsgController();  //用绝对路径找
            $focusmsg->setxcache(session('u_id'),"参与试吃活动",'http://www.xiangtws.com'.$_SERVER['REQUEST_URI']);
        }//end if
        //未关注的存储到xcache中，程序轮询检测（关注后推送最近浏览的商品信息）-end
    }//end fun


    public function index(){
        $state = I('get.state')? I('get.state') : 0;
        $type = $state? $state : I('post.type');
        $u_id = session('u_id');
        switch ($type){
            case 1:
                $where = " ";//所有的
                break;
            case 2:
                $where = "fo.state IN (0,1,6) AND ";//申请状态
                break;
            case 3:
                $where = "fo.state = 2 AND ";//已发货状态
                break;
            case 4:
                $where = "fo.state = 3 AND ";//待核销状态
                break;
            case 5:
                $where = "fo.state = 4 AND ";//待评价状态
                break;
        }

        //全部
        $foretaste = M("foretaste_order")->alias('fo')
            ->join("xtws_foretaste_goods fg ON fo.g_id = fg.id","LEFT")
            ->where($where." fo.u_id = {$u_id}")
            ->order('fo.id desc')
            ->field("fo.*,fg.category,fg.title,fg.h_imgs")
            ->select();


        foreach ($foretaste as $k => $v){
            //         获取订单排行信息
            $foretaste_order = M("foretaste_order")
                ->where("g_id = {$v['g_id']} AND state in(0,1,2,3,4,5)")
                ->order("population DESC,usetime,u_id")
                ->select();
            //         获取排名
            foreach($foretaste_order as $key => $val){
                if ($val['id'] == $v['id']){
                    $rangking = $key+1;
                }//end if
            }//end foreach

            //状态显示信息拼接
            switch ($v['state']){
                case 0:
                    $foretaste[$k]['state_content'] = "还差<span style='font-size: 20px;color: #f9790b;'>".(8-$v['population']) ."</span>人完成集赞";
                    $foretaste[$k]['state'] = "申请中";
                    break;
                case 1:
                    $foretaste[$k]['state_content'] = "您的试吃申请已成功，请查看详情！";
                    $foretaste[$k]['state'] = "申请成功";
                    break;
                case 2:
                    $foretaste[$k]['state'] = "已发货";
                    break;
                case 3:
                    $foretaste[$k]['state'] = "待核销";
                    break;
                case 4:
                    $foretaste[$k]['state'] = "待评价";
                    break;
                case 5:
                    $foretaste[$k]['state'] = "已评价";
                    break;
                case 6:
                    //失败状态显示
                    $foretaste[$k]['state_content'] = "因未能集满8个赞，失败了！";
                    $foretaste[$k]['state'] = "申请失败";
                    break;
            }//end switch
        }//end foreach

        $this->assign('type',$type);
        $this->assign('foretaste',$foretaste);
        $this->display("order-sc");
    }//end fun index()

    //详情页
    public function order(){
        $order_id = $_GET['oid'];
        if (!empty($order_id)){
            $order = M("foretaste_order")->where("id = {$order_id}")->find();
            $goods = M("foretaste_goods")->where("id = {$order['g_id']}")->find();
            //获取点赞的用户信息
            $log = M("foretaste_order_log")->where("o_id = {$order['id']}")->select();
            foreach ($log as $k => $v){
                $log_member[$k] = getMember($v['u_id'],'nickname,avatar');
                $log_member[$k]['nickname'] =mb_substr($log_member[$k]['nickname'],0,8,'utf-8');//截断过长的用户昵称
                $log_member[$k]['addtime'] = $v['addtime'];
            }

            $member = getMember($order['u_id']);
            $store = M("shop_store")->where("c_id = {$member['c_id']}")->find();//该社区店铺信息
            $recommend = M('shop_recommend')->where("u_id = {$member['id']}")->find();//是否推荐店铺
        }

        /*--------------完成所用时间处理-start--------------*/

        $hour = intval($order['usetime']/60/60);//小时

        $usetime = $order['usetime']-$hour*60*60;//去除小时后剩余时间
        $minute = intval($usetime/60);//分钟

        $second = $usetime-$minute*60;//秒

        $order[$k]['str_time'] = '';
        //      字符串拼接时间
        //      小时
        if ($hour != 0){
            $hour=str_pad($hour,2,"0",STR_PAD_LEFT);//自动补零
            $order['str_time'] .= $hour.'小时';
        }//end if

        //      分钟
        if ($minute != 0){
            $minute=str_pad($minute,2,"0",STR_PAD_LEFT);//自动补零
            $order['str_time'] .= $minute.'分钟';
        }//end if

        //      秒
        $order['str_time'] .= $second.'秒';
        /*--------------完成所用时间处理-end--------------*/
        if ($order['state'] == 5){
            /*--------------评价分享-start---------------------*/
            $u_id = session('u_id');
            $e_info = M('foretaste_evaluate')->where('o_id = '.$order_id)->find();  //评价详情
            $e_info['focus'] = session('focus');//是否关注
            $e_info['goodstitle'] = M('foretaste_goods')->where('id = '.$e_info['g_id'])->getField('title');  //评价详情

            $m_info = M('member')->where('id = '.$e_info['u_id'])->field('nickname,avatar,hometown')->find();      //评价用户详情
            if ($e_info['is_inco'] == 0){
                $m_info['nickname']='匿名';
            }
            $e_info['pic'] = $var=explode(",",$e_info['pic']);         //处理评价图片
            $comment = M('evaluate_comment')->table(C('DB_PREFIX')."evaluate_comment as c")  //评价-评论详情
            ->join(C('DB_PREFIX')."member as m ON m.id=c.send_id")
                ->field('c.*,m.nickname,m.avatar,m.hometown')
                ->where('e_id = '.$e_info['id'] .' AND accept_id ='.$e_info['u_id'])
                ->order('id desc')
                ->select();
            $count = M('evaluate_comment')->where('e_id = '.$e_info['id'])->count();    //评论总数

            //微信分享
            $wxshare=new shareModel(C('WX_API.appid'),C('WX_API.secret'));
            $signPackage=$wxshare->getSignPackage();
            /*
            *
            array(6) {
              ["appId"] => string(18) "wx6a0daaedc4d00100"
              ["nonceStr"] => string(16) "5cKMHQADQTbRkv2f"
              ["timestamp"] => int(1527576256)
              ["url"] => string(59) "http://www.xiangtws.com/index.php/Wx/Prodetail/index/id/20/"
              ["signature"] => string(40) "a70ef78304bc4f5558439b65955119806e4fb3fe"
              ["rawString"] => string(205) "jsapi_ticket=HoagFKDcsGMVCIY2vOjf9raVdUJqZ1stwmkyXwhMyovuJhCTHjtpRnNxRJSVQ0UacAdrqz97vWdzjRU3Dp-YYw&noncestr=5cKMHQADQTbRkv2f*tamp=1527576256&url=http://www.xiangtws.com/index.php/Wx/Prodetail/index/id/20/"
            }
            *
            */		//dump($signPackage);
            $this->assign('signPackage',$signPackage);//微信数据
            //微信分享-end3

            $this->assign('u_id',$u_id);
            $this->assign('e_info',$e_info);
            $this->assign('m_info',$m_info);
            $this->assign('comment',$comment);
            $this->assign('count',$count);

            /*--------------评价分享-end---------------------*/
        }//end if

        //总成功订单
        $goods['sumorder'] = M("foretaste_order")->where("state in (1,2,3,4,5)")->getField('count(id)');//订单信息

        $this->assign($order);
        $this->assign('goods',$goods);
        $this->assign('store',$store);
        $this->assign('recommend',$recommend);
        $this->assign('log',$log_member);
        //辨别用户
        if ($u_id != $e_info['u_id']){

            //未关注的存储到xcache中，程序轮询检测（关注后推送最近浏览的商品信息）-start
            if(session('focus')==0 && session('u_id')>0){
                $focusmsg=new \Wx\Controller\AutofocusmsgController();  //用绝对路径找
                $focusmsg->setxcache(session('u_id'),"来乡土味士，吃天然菜，评选扶贫大使！",'http://www.xiangtws.com'.$_SERVER['REQUEST_URI']);
            }//end if
            //未关注的存储到xcache中，程序轮询检测（关注后推送最近浏览的商品信息）-end

            $this->display('commentdetail-fx');
        }else{
            $this->display("orderdetail-sc");
        }
    }//end fun order()

    // 添加评价
    public function addEva(){
        if(IS_POST){
            $post = I('post.');
            $post['u_id'] = session('u_id');    // 用户id
            if($post['img_1']!=''||$post['img_2']!=''||$post['img_3']!=''){//如果有图片便进行处理
                $post['pic'] = $post['img_1'].$post['img_2'].$post['img_3'];    //拼接图片路径
                $post['pic'] = substr($post['pic'],0,strlen($post['pic'])-1);   //去掉路径最后的英文逗号
            }// end if
            $post['addtime'] = time();
            $res = M('foretaste_evaluate')->add($post);
            if($res) {
                // 更新订单状态-已评价
                $eva = M('foretaste_order')->where('id = '.$post['o_id'])->setField('state',5);
                if ($eva){
                    /*---------------------------------添加排名记录-start-------------------------------------*/
                    $helppoor = M("helppoor")->where("state = 1")->getField('id');//获取排行活动id
                    $is_new = M("foretaste_ranking")->where("u_id = {$post['u_id']} AND h_id = {$helppoor}")->find();//查看是否有排名记录
                    if (isset($is_new)){
                        $e_id = $is_new['e_id'].",".$res;//参加排名评论id
                        M("foretaste_ranking")->where("id = {$is_new['id']}")->save(['e_id'=>$e_id]);
                    }else{
                        $helppoor_id = M("helppoor")->where("state = 1")->getField('id');//排行活动id
                        if (isset($helppoor)){
                            $ranking = array(
                                'u_id' => $post['u_id'],//获取用户id
                                'c_id' => getMember($post['u_id'],'c_id'),//获取小区id
                                'e_id' => $res,//评论id
                                'h_id' => $helppoor_id,//排行活动id
                                'addtime' => time()
                            );
                            M("foretaste_ranking")->add($ranking);
                        }//end if
                    }//end if
                    /*---------------------------------添加排名记录-end-------------------------------------*/

                    $this->ajaxReturn(['state'=>0,'info'=>'添加成功'],"JSON");
                }//end if
            }else{
                $this->ajaxReturn(['state'=>1,'info'=>'添加失败，请检查'],"JSON");

            }// end if
        }else{
            $o_id = intval(I('oid'));  //订单id
            $order = M("foretaste_order")->where("id = {$o_id}")->getField('g_id');
            $g_id = intval($order);  // 商品id
            $this -> assign('o_id',$o_id);
            $this -> assign('g_id',$g_id);
            $this->display('evaluate');
        }// end if
    }// end fun addEva()

}//end class